package com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_business

import android.util.Log
import com.facebook.ads.NativeAd
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.bean.ConfigResultBean
import com.horoscope.astrology.zodiac.signs.free.bean.NativeAdBean
import com.horoscope.astrology.zodiac.signs.free.utils.EventType
import com.horoscope.astrology.zodiac.signs.free.utils.FlurryEventUtil
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ADConfig
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_implement.LoadFacebookAd
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_implement.LoadGoogleAd
import com.horoscope.astrology.zodiac.signs.free.utils.interfaceUtils.FacebookNativeListener
import com.horoscope.astrology.zodiac.signs.free.utils.interfaceUtils.GoogleNativeListener
import java.util.*
import java.util.concurrent.atomic.AtomicInteger

class ADNativeManager private constructor() : GoogleNativeListener, FacebookNativeListener {

    private var adQueue: PriorityQueue<ConfigResultBean.AdInfo>? = null
    private val nativeList =
        Collections.synchronizedList(ArrayList<ArrayList<ConfigResultBean.AdInfo>>())

    private var allGroupSize = 0        // 总共有几组 (目前3组)
    private var nCurrentInGroupSize = 0 // 当前使用这一组大小 (2个)

    @Volatile
    private var nCurrentGroupIndex = AtomicInteger(0)  // 当前请求的是第几组

    @Volatile
    private var errorNum = AtomicInteger(0) //记录当前广告ID是否请求成功

    @Volatile
    private var successNum = AtomicInteger(0) //记录当前广告ID是否请求成功

    companion object {
        val mInstance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            ADNativeManager()
        }
    }

    override fun onFacebookNativeFailed(e: String) {
        Log.e("===", "Facebook失败 当前是第 $nCurrentGroupIndex 组")
        errorNum.addAndGet(1)
        isRequestCurrentGroupNextID(nCurrentGroupIndex.get())
    }

    override fun onGoogleNativeFailed(e: String) {
        Log.e("===", "AdMob失败 当前是第 $nCurrentGroupIndex 组")
        errorNum.addAndGet(1)
        isRequestCurrentGroupNextID(nCurrentGroupIndex.get())
    }

    override fun onFacebookNativeLoad(bean: ConfigResultBean.AdInfo, nativeAd: NativeAd) {
        successNum.set(1)
        createAndAdd(bean)
    }

    override fun onGoogleNativeLoad(bean: ConfigResultBean.AdInfo) {
        successNum.set(1)
        createAndAdd(bean)
    }

    fun createAndAdd(bean: ConfigResultBean.AdInfo) {
        if (adQueue == null) {
            adQueue = createQueue(nCurrentInGroupSize)
        }
        adQueue!!.offer(bean)
    }

    @Synchronized
    private fun isRequestCurrentGroupNextID(index: Int) {
        if (nativeList.size > 0) {
            if (errorNum.get() == nativeList[if (index < nativeList.size) index else 0].size) {
                errorNum.set(0)
                requestNextGroup(index)
            }
        }
    }

    private fun requestNextGroup(index: Int) {
        val nextIndex = index + 1
        if (allGroupSize > 0) {
            if (nextIndex < allGroupSize) {
                nCurrentInGroupSize = nativeList[nextIndex].size
                if (adQueue == null) adQueue = createQueue(nCurrentInGroupSize)
                nativeGroupRequest(nextIndex)
            }
        }
    }

    fun getNativeAdBean(placement: String): NativeAdBean? {
        val time: Int = ((System.currentTimeMillis() - AppSettingManager.readLong(
            "nativeTime",
            0
        )) / 1000f).toInt()
        if (time in 1..199) {
            AppSettingManager.saveLong(System.currentTimeMillis(), "nativeTime")
        }
        var resBean: NativeAdBean? = NativeAdBean()

        FlurryEventUtil.putDataToEvent(EventType.TYPE_AD_SHOULD_DISPLAY, "type", placement)

        if (adQueue == null) { // splash里还没加载完就展示了
            adQueue = createQueue(nCurrentInGroupSize)
            return null
        }

        if (nativeList.size > 0) {
            if (adQueue!!.isEmpty() && nCurrentGroupIndex.get() >= nativeList.size) {
                FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Native", "None_$time")
                nativeGroupRequest(0)
                return getNextAd(resBean!!)
            } else {
                val adBean = adQueue!!.poll()
                resBean!!.facebookNativeAD = null
                resBean.googleNativeAd = null
                if (adBean != null) {
                    resBean.adInfo = adBean
                    when (adBean.advertiser) {
                        ADConfig.FB -> {
                            resBean.facebookNativeAD =
                                LoadFacebookAd.mInstance.getFacebookNativeAd(placement, time)
                        }
                        ADConfig.ADMOB -> {
                            resBean.googleNativeAd =
                                LoadGoogleAd.mInstance.getNativeAd(placement, time)
                        }
                    }
                } else {
                    FlurryEventUtil.putDataToEvent(
                        EventType.TYPE_IS_READY,
                        "Native",
                        "None_$time"
                    )
                    resBean = getNextAd(resBean)
                }
            }

            // 所有组别都失败下一次展示从头开始请求
            if (resBean!!.facebookNativeAD == null && resBean.googleNativeAd == null && adQueue!!.isEmpty() && nCurrentGroupIndex.get() >= nativeList.size - 1) {
                nCurrentGroupIndex.set(0)
                nativeGroupRequest(0)
                LoadFacebookAd.mInstance.loadNativeManager()
            }

            //组内有任意一个请求成功从头开始请求
            if (adQueue!!.isEmpty() && successNum.get() > 0) {
                errorNum.set(0)
                successNum.set(0)
                nativeGroupRequest(0)
            }
        } else {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Native", "None_$time")
            return getNextAd(resBean!!)
        }

        return resBean
    }

    private fun getNextAd(bean: NativeAdBean): NativeAdBean? {
        bean.adInfo.advertiser = ADConfig.FB
        if (LoadFacebookAd.mInstance.mNativeAdsManager != null) {
            bean.facebookNativeAD =
                LoadFacebookAd.mInstance.mNativeAdsManager!!.nextNativeAd()
            return bean
        }
        return null
    }

    fun initConfig(bean: ConfigResultBean.ConfigResultBeanData) {
        LoadGoogleAd.mInstance.setGoogleNativeListener(this)
        LoadFacebookAd.mInstance.setFacebookNativeListener(this)
        nativeList.clear()
        nativeList.addAll(bean.ADID.Native)
        allGroupSize = nativeList.size

        nCurrentInGroupSize = if (nativeList.isNotEmpty()) nativeList[0].size else 0
        AppSettingManager.saveLong(System.currentTimeMillis(), "nativeTime")
        nativeGroupRequest(0)
    }

    private fun createQueue(size: Int): PriorityQueue<ConfigResultBean.AdInfo> {
        var reSize = 2
        if (size >= 1) {
            reSize = size
        }
        return PriorityQueue(reSize,
            Comparator<ConfigResultBean.AdInfo> { s1, s2 ->
                s2.cpminfo.toInt() - s1.cpminfo.toInt()
            })
    }

    @Synchronized
    private fun nativeGroupRequest(index: Int) {
        if (nativeList.size > 0) {
            nCurrentGroupIndex.set(index)
            Log.e("===", "当前请求第 $index 组")
            nativeList[if (index < nativeList.size) index else 0].forEach { it ->
                when (it.advertiser) {
                    ADConfig.ADMOB -> {
                        LoadGoogleAd.mInstance.initNativeAd(it)
                    }
                    ADConfig.FB -> {
                        LoadFacebookAd.mInstance.loadNativeAd(it)
                    }
                }
            }
        }
    }

//    @Synchronized
//    fun getNativeFirst() {
//        if (nativeList.size > 0) {
//            nativeList[0].forEach { it ->
//                when (it.advertiser) {
//                    ADConfig.ADMOB -> {
//                        LoadGoogleAd.mInstance.initNativeAd(it)
//                    }
//                    ADConfig.FB -> {
//                        LoadFacebookAd.mInstance.loadNativeAd(it)
//                    }
//                }
//            }
//        }
//    }


}